package com.example.pilipili.utils;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FTPU {
    //服务器IP
    private static final String  FTP_ADDRESS = "47.98.145.148";
    //端口号
    private static final int FTP_PORT = 21;
    //用户名
    private static final String FTP_USERNAME = "admin";
    //密码
    private static final String FTP_PASSWORD = "123456";


    public static String uploadFile(MultipartFile file, String dir) throws IOException {
        final InputStream inputStream = file.getInputStream();
        final String fileName = file.getOriginalFilename();
        final String suffix = fileName.substring(fileName.lastIndexOf("."));
        final String finalName = UUID.randomUUID() + suffix;


        FTPClient ftp = new FTPClient();

        try {
            int reply;
            // 启用调试模式
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(new FileWriter("ftp.log")), true));
            ftp.connect(FTP_ADDRESS, FTP_PORT);
            ftp.login(FTP_USERNAME, FTP_PASSWORD);
//            ftp.setConnectTimeout(150000) ;
            ftp.enterLocalPassiveMode();
            ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);//设置传输方式为流方式
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return null;
            }

            // 添加保存路径
            if (dir != null && !dir.isEmpty()) {
                ftp.changeWorkingDirectory(dir);
                ftp.makeDirectory(dir);
                ftp.changeWorkingDirectory(dir);
            }

            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

            ftp.storeFile(finalName, inputStream);
            inputStream.close();
            ftp.logout();
        }catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage()) ;
        } finally {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        }

        return dir+"/"+finalName;
    }



}
